import logging

from common_ihrm.use_1 import log
import pymysql


class db_ihrm:
    @classmethod
    def connet(cls):
        # 建立连接,数据库链接对象 cancan
        cls.db = pymysql.connect(host="127.0.0.1", port=3306, user="root",
                                 password="root", database="ihrm", charset="utf8")
        # 获取游标,创建一个光标对象
        cls.cursor = cls.db.cursor()
        log(ob="file", filename="C:\pythonfile\ihrm\report\runlog.txt")
        logging.info("数据库连接成功")
        return cls.cursor

    @classmethod
    def close_db(cls):
        cls.cursor.close()  # 关闭游标
        cls.db.close()  # 关闭数据库连接
        logging.info('数据库关闭成功')

    @classmethod
    def excute_sql(cls, sql):
        try:
            # 执行语句
            cls.cursor.execute(sql)
            res = cls.db.affected_rows()  # 影响了几条数据
            print("res=", res)
            # 向数据库提交数据
            cls.db.commit()
            print("sql语句执行成功")
            logging.info('sql语句执行成功')
        except:
            logging.error('sql语句执行失败')
            print('sql语句执行失败')
